package yxxy;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

	public static void main(String[] args) {
		SemaphoreTest test = new SemaphoreTest();
		test.execute();
	}
	private void execute () {
		final Semaphore s = new Semaphore(2);
		ExecutorService threadPool = Executors.newCachedThreadPool();
		for(int i=0;i<20;i++) {
			threadPool.execute(new MyTask(s, i+1));
		}
		threadPool.shutdown();
	}
	class MyTask implements Runnable{
		private Semaphore s;
		private int user;
		
		public MyTask(Semaphore s, int user) {
			super();
			this.s = s;
			this.user = user;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				s.acquire();
				
				System.out.println("用户【"+user+"】进入窗口买票");
				Thread.sleep((long)(Math.random()*10000));
				System.out.println("用户【"+user+"】买票完成，准备离开");
				Thread.sleep((long)(Math.random()*10000));
				System.out.println("用户【"+user+"】离开窗口");
				s.release();
			}catch( InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
}